package com.hsq.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPFileUploadServer_1 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("等待客户端连接...");
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        String downLoadFileName = "";
        while ((len = inputStream.read(bytes)) != -1) {
            downLoadFileName += new String(bytes, 0, len);
        }

        System.out.println("希望下载的文件名是: " + downLoadFileName);
        String resFileName = "";
        if ("tetris".equals(downLoadFileName)) {
            resFileName = "D:\\Study\\C\\training\\day6\\tetris.mp3";
        }
        else {
            System.out.println("无该文件");
            inputStream.close();
            socket.close();
            serverSocket.close();
            return ;
        }

        BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(resFileName));

        byte[] b = StreamUtils.streamToByteArray(bis);

        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        bos.write(b);
        socket.shutdownOutput();

        bos.close();
        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();

    }
}
